/**
 * 电机全维度运行监测数据表管理模块
 */

let aapDataAPI_BASE = '/api/feibiao/knowledge/aap-data';

document.addEventListener('DOMContentLoaded', function() {
    if (typeof API_BASE !== 'undefined') {
        aapDataAPI_BASE = `${API_BASE}/feibiao/knowledge/aap-data`;
    }
});

function loadAapDataList(page = 0, size = 10, sort = 'id,asc') {
    const mainContent = document.getElementById('mainContent');
    if (!mainContent) return;
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    fetch(`${aapDataAPI_BASE}?page=${page}&size=${size}&sort=${sort}`)
        .then(response => {
            if (!response.ok) throw new Error('请求失败: ' + response.statusText);
            return response.json();
        })
        .then(data => {
            renderAapDataTable(data, sort);
        })
        .catch(error => {
            mainContent.innerHTML = `<div class="error-container">加载失败: ${error.message}</div>`;
            showMessage('获取电机数据失败: ' + error.message, 'error');
        });
}

function renderAapDataTable(data, sort = 'id,desc') {
    const mainContent = document.getElementById('mainContent');
    let html = `
        <div class="content-header">
            <h2 class="content-title">电机数据表</h2>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="showAapDataForm()"></i> 新增</button>
            </div>
        </div>
        <div class="content-toolbar">
            <div class="search-box">
                <input type="text" class="search-input" id="aapMotorIdInput" placeholder="电机ID...">
                <input type="datetime-local" id="aapStartTimeInput" style="width:180px;" placeholder="开始时间">
                <input type="datetime-local" id="aapEndTimeInput" style="width:180px;" placeholder="结束时间">
                <button class="search-btn" onclick="searchAapData()">搜索</button>
            </div>
            <div class="sort-container">
                <label for="aapSortSelect">排序方式:</label>
                <select id="aapSortSelect" onchange="changeAapDataSorting()">
                    <option value="id,desc">ID降序</option>
                    <option value="id,asc">ID升序</option>
                    <option value="timestamp,desc">采集时间降序</option>
                    <option value="timestamp,asc">采集时间升序</option>
                </select>
            </div>
        </div>
        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>电机ID</th>
                        <th>采集时间</th>
                        <th>转速(rpm)</th>
                        <th>三相电压</th>
                        <th>三相电流</th>
                        <th>温度数据</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
    `;
    if (data.content && data.content.length > 0) {
        data.content.forEach(item => {
            html += `
                <tr>
                    <td>${item.id}</td>
                    <td>${item.motorId}</td>
                    <td>${formatDate(item.timestamp)}</td>
                    <td>${item.speed}</td>
                    <td>${jsonPreview(item.voltagePhases)}</td>
                    <td>${jsonPreview(item.currentPhases)}</td>
                    <td>${jsonPreview(item.temperatureData)}</td>
                    <td class="table-actions">
                        <a href="javascript:void(0)" onclick="viewAapData('${item.id}')">查看</a>
                        <a href="javascript:void(0)" onclick="editAapData('${item.id}')">编辑</a>
                        <a href="javascript:void(0)" class="delete" onclick="deleteAapData('${item.id}')">删除</a>
                    </td>
                </tr>
            `;
        });
    } else {
        html += '<tr><td colspan="8" style="text-align:center;">暂无数据</td></tr>';
    }
    html += `</tbody></table></div>`;
    if (data.totalPages > 1) {
        html += `
            <div class="pagination">
                <button class="page-btn" onclick="loadAapDataList(${Math.max(0, data.number - 1)}, ${data.size}, '${sort}')" ${data.first ? 'disabled' : ''}>&laquo; 上一页</button>
                <span class="page-info">第 ${data.number + 1} 页，共 ${data.totalPages} 页</span>
                <button class="page-btn" onclick="loadAapDataList(${Math.min(data.totalPages - 1, data.number + 1)}, ${data.size}, '${sort}')" ${data.last ? 'disabled' : ''}>下一页 &raquo;</button>
            </div>
        `;
    }
    mainContent.innerHTML = html;
    if (document.getElementById('aapSortSelect')) {
        document.getElementById('aapSortSelect').value = sort;
    }
}

function changeAapDataSorting() {
    const sortValue = document.getElementById('aapSortSelect').value;
    loadAapDataList(0, 10, sortValue);
}

function searchAapData() {
    const motorId = document.getElementById('aapMotorIdInput').value.trim();
    const startTime = document.getElementById('aapStartTimeInput').value;
    const endTime = document.getElementById('aapEndTimeInput').value;
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据搜索中...</div>';
    let url = `${aapDataAPI_BASE}/search?`;
    if (motorId) url += `motorId=${encodeURIComponent(motorId)}&`;
    if (startTime) url += `startTime=${encodeURIComponent(startTime)}&`;
    if (endTime) url += `endTime=${encodeURIComponent(endTime)}&`;
    fetch(url)
        .then(response => {
            if (!response.ok) throw new Error('搜索请求失败: ' + response.statusText);
            return response.json();
        })
        .then(data => {
            renderAapDataTable(data);
        })
        .catch(error => {
            mainContent.innerHTML = `<div class="error-container">搜索失败: ${error.message}</div>`;
            showMessage('搜索失败: ' + error.message, 'error');
        });
}

function showAapDataForm(data = null) {
    const mainContent = document.getElementById('mainContent');
    const isEdit = !!data;
    mainContent.innerHTML = `
        <div class="content-header">
            <h2 class="content-title">${isEdit ? '编辑' : '新增'}电机数据</h2>
            <button class="btn btn-default" onclick="loadAapDataList()"><i class="fa fa-list"></i> 返回列表</button>
        </div>
        <form id="aapDataForm" class="data-form" onsubmit="submitAapDataForm(event)">
            ${isEdit ? `<input type="hidden" id="id" name="id" value="${data.id}">` : ''}
            <div class="form-group">
                <label for="motorId">电机ID <span class="required">*</span></label>
                <input type="text" id="motorId" name="motorId" class="form-control" maxlength="10" value="${isEdit ? data.motorId : ''}" required>
            </div>
            <div class="form-group">
                <label for="timestamp">采集时间 <span class="required">*</span></label>
                <input type="datetime-local" id="timestamp" name="timestamp" class="form-control" value="${isEdit ? formatDateTimeLocal(data.timestamp) : ''}" required>
            </div>
            <div class="form-group">
                <label for="speed">转速(rpm) <span class="required">*</span></label>
                <input type="number" id="speed" name="speed" class="form-control" min="0" max="20000" step="0.01" value="${isEdit ? data.speed : ''}" required>
            </div>
            <div class="form-group">
                <label for="voltagePhases">三相电压[U,V,W] (JSON数组) <span class="required">*</span></label>
                <input type="text" id="voltagePhases" name="voltagePhases" class="form-control" value="${isEdit ? data.voltagePhases : '[0,0,0]'}" required>
                <small class="form-text">如: [220,220,220]</small>
            </div>
            <div class="form-group">
                <label for="currentPhases">三相电流[U,V,W] (JSON数组) <span class="required">*</span></label>
                <input type="text" id="currentPhases" name="currentPhases" class="form-control" value="${isEdit ? data.currentPhases : '[0,0,0]'}" required>
                <small class="form-text">如: [10,10,10]</small>
            </div>
            <div class="form-group">
                <label for="temperatureData">温度数据[绕组,轴承,外壳,环境] (JSON数组) <span class="required">*</span></label>
                <input type="text" id="temperatureData" name="temperatureData" class="form-control" value="${isEdit ? data.temperatureData : '[0,0,0,0]'}" required>
                <small class="form-text">如: [60,40,35,25]</small>
            </div>
            <div class="form-group">
                <label for="vibrationData">三轴振动时域[XYZ] (JSON数组) <span class="required">*</span></label>
                <input type="text" id="vibrationData" name="vibrationData" class="form-control" value="${isEdit ? data.vibrationData : '[0,0,0]'}" required>
                <small class="form-text">如: [0.01,0.02,0.01]</small>
            </div>
            <div class="form-group">
                <label for="vibrationSpectrum">三轴振动频谱[XYZ] (JSON数组) <span class="required">*</span></label>
                <input type="text" id="vibrationSpectrum" name="vibrationSpectrum" class="form-control" value="${isEdit ? data.vibrationSpectrum : '[0,0,0]'}" required>
                <small class="form-text">如: [0.1,0.2,0.1]</small>
            </div>
            <div class="form-group">
                <label for="ambientConditions">环境条件[温度,湿度,压力] (JSON数组) <span class="required">*</span></label>
                <input type="text" id="ambientConditions" name="ambientConditions" class="form-control" value="${isEdit ? data.ambientConditions : '[0,0,0]'}" required>
                <small class="form-text">如: [25,60,101.3]</small>
            </div>
            <div class="form-group">
                <label for="performanceMetrics">性能指标[效率,功率因数,输入功率,输出功率] (JSON数组) <span class="required">*</span></label>
                <input type="text" id="performanceMetrics" name="performanceMetrics" class="form-control" value="${isEdit ? data.performanceMetrics : '[0,0,0,0]'}" required>
                <small class="form-text">如: [95,0.85,10,9.5]</small>
            </div>
            <div class="form-group">
                <label for="historicalStates">历史状态 (JSON数组) <span class="required">*</span></label>
                <textarea id="historicalStates" name="historicalStates" class="form-control" required>${isEdit ? data.historicalStates : '[]'}</textarea>
                <small class="form-text">如: [{"timestamp":"2024-01-01T12:00:00","value":1.0}]</small>
            </div>
            <div class="form-group">
                <label for="maintenanceHistory">维护历史 (JSON数组) <span class="required">*</span></label>
                <textarea id="maintenanceHistory" name="maintenanceHistory" class="form-control" required>${isEdit ? data.maintenanceHistory : '[]'}</textarea>
                <small class="form-text">如: [{"date":"2024-01-01","desc":"更换轴承"}]</small>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">保存</button>
                <button type="button" class="btn btn-default" onclick="loadAapDataList()">取消</button>
            </div>
        </form>
    `;
}

function submitAapDataForm(event) {
    event.preventDefault();
    const id = document.getElementById('id')?.value;
    const motorId = document.getElementById('motorId').value.trim();
    const timestamp = document.getElementById('timestamp').value;
    const speed = parseFloat(document.getElementById('speed').value);
    const voltagePhases = document.getElementById('voltagePhases').value.trim();
    const currentPhases = document.getElementById('currentPhases').value.trim();
    const temperatureData = document.getElementById('temperatureData').value.trim();
    const vibrationData = document.getElementById('vibrationData').value.trim();
    const vibrationSpectrum = document.getElementById('vibrationSpectrum').value.trim();
    const ambientConditions = document.getElementById('ambientConditions').value.trim();
    const performanceMetrics = document.getElementById('performanceMetrics').value.trim();
    const historicalStates = document.getElementById('historicalStates').value.trim();
    const maintenanceHistory = document.getElementById('maintenanceHistory').value.trim();
    if (!motorId || !timestamp || isNaN(speed) || !voltagePhases || !currentPhases || !temperatureData || !vibrationData || !vibrationSpectrum || !ambientConditions || !performanceMetrics || !historicalStates || !maintenanceHistory) {
        showMessage('请填写所有必填字段', 'error');
        return;
    }
    // 简单校验JSON格式
    try {
        JSON.parse(voltagePhases);
        JSON.parse(currentPhases);
        JSON.parse(temperatureData);
        JSON.parse(vibrationData);
        JSON.parse(vibrationSpectrum);
        JSON.parse(ambientConditions);
        JSON.parse(performanceMetrics);
        JSON.parse(historicalStates);
        JSON.parse(maintenanceHistory);
    } catch (e) {
        showMessage('请确保所有JSON字段格式正确', 'error');
        return;
    }
    const data = {
        motorId,
        timestamp: new Date(timestamp).toISOString(),
        speed,
        voltagePhases,
        currentPhases,
        temperatureData,
        vibrationData,
        vibrationSpectrum,
        ambientConditions,
        performanceMetrics,
        historicalStates,
        maintenanceHistory
    };
    if (id) data.id = parseInt(id);
    const method = id ? 'PUT' : 'POST';
    const url = id ? `${aapDataAPI_BASE}/${id}` : aapDataAPI_BASE;
    fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                try {
                    const error = JSON.parse(text);
                    throw new Error(error.message || error.error || '保存失败');
                } catch (e) {
                    throw new Error(text || '保存失败');
                }
            });
        }
        return response.json();
    })
    .then(() => {
        showMessage(`${id ? '更新' : '创建'}成功!`, 'success');
        loadAapDataList();
    })
    .catch(error => {
        showMessage('保存失败: ' + error.message, 'error');
    });
}

function viewAapData(id) {
    fetch(`${aapDataAPI_BASE}/${id}`)
        .then(response => {
            if (!response.ok) throw new Error('获取详情失败: ' + response.statusText);
            return response.json();
        })
        .then(data => {
            showAapDataDetail(data);
        })
        .catch(error => {
            showMessage('获取详情失败: ' + error.message, 'error');
        });
}

function showAapDataDetail(data) {
    const mainContent = document.getElementById('mainContent');
    let html = `
        <div class="content-header">
            <h2 class="content-title">电机数据详情</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadAapDataList()"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
        <div class="data-detail">
            <div class="detail-group"><label>ID:</label><div>${data.id || '--'}</div></div>
            <div class="detail-group"><label>电机ID:</label><div>${data.motorId || '--'}</div></div>
            <div class="detail-group"><label>采集时间:</label><div>${formatDate(data.timestamp) || '--'}</div></div>
            <div class="detail-group"><label>转速(rpm):</label><div>${data.speed || '--'}</div></div>
            <div class="detail-group"><label>三相电压:</label><pre>${jsonPretty(data.voltagePhases)}</pre></div>
            <div class="detail-group"><label>三相电流:</label><pre>${jsonPretty(data.currentPhases)}</pre></div>
            <div class="detail-group"><label>温度数据:</label><pre>${jsonPretty(data.temperatureData)}</pre></div>
            <div class="detail-group"><label>三轴振动时域:</label><pre>${jsonPretty(data.vibrationData)}</pre></div>
            <div class="detail-group"><label>三轴振动频谱:</label><pre>${jsonPretty(data.vibrationSpectrum)}</pre></div>
            <div class="detail-group"><label>环境条件:</label><pre>${jsonPretty(data.ambientConditions)}</pre></div>
            <div class="detail-group"><label>性能指标:</label><pre>${jsonPretty(data.performanceMetrics)}</pre></div>
            <div class="detail-group"><label>历史状态:</label><pre>${jsonPretty(data.historicalStates)}</pre></div>
            <div class="detail-group"><label>维护历史:</label><pre>${jsonPretty(data.maintenanceHistory)}</pre></div>
            <div class="detail-actions">
                <button class="btn btn-primary" onclick="editAapData('${data.id}')"><i class="fa fa-edit"></i> 编辑</button>
                <button class="btn btn-danger" onclick="deleteAapData('${data.id}')"><i class="fa fa-trash"></i> 删除</button>
                <button class="btn btn-default" onclick="loadAapDataList()"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
    `;
    mainContent.innerHTML = html;
}

function editAapData(id) {
    fetch(`${aapDataAPI_BASE}/${id}`)
        .then(response => {
            if (!response.ok) throw new Error('获取数据失败: ' + response.statusText);
            return response.json();
        })
        .then(data => {
            showAapDataForm(data);
        })
        .catch(error => {
            showMessage('获取数据失败: ' + error.message, 'error');
        });
}

function deleteAapData(id) {
    if (!confirm('确定要删除这条记录吗？此操作不可恢复！')) return;
    fetch(`${aapDataAPI_BASE}/${id}`, { method: 'DELETE' })
        .then(response => {
            if (!response.ok) throw new Error('删除失败: ' + response.statusText);
            showMessage('删除成功!', 'success');
            loadAapDataList();
        })
        .catch(error => {
            showMessage('删除失败: ' + error.message, 'error');
        });
}

function formatDate(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

function formatDateTimeLocal(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toISOString().slice(0, 16);
}

function jsonPreview(str) {
    try {
        const arr = JSON.parse(str);
        if (Array.isArray(arr)) {
            return '[' + arr.map(v => typeof v === 'object' ? '...' : v).join(',') + ']';
        }
        return JSON.stringify(arr);
    } catch (e) {
        return '-';
    }
}

function jsonPretty(str) {
    try {
        return JSON.stringify(JSON.parse(str), null, 2);
    } catch (e) {
        return str || '-';
    }
}

function showMessage(msg, type) {
    // 检查是否有全局的 showMessage 函数
    if (typeof window.showMessage === 'function' && window.showMessage !== showMessage) {
        window.showMessage(msg, type);
    } else {
        // 如果没有全局函数，使用简单的 alert
        alert(msg);
    }
} 